# -*- coding: utf-8 -*-
"""
 Created by wq.wang on 2017/12/22
"""
import logging
from sanic import Sanic
from settings import config

from sanic.response import json

from wserver.base.server import WServer
from wserver.base.service import SERVICE, RESTFUL_METHOD

_logger = logging.getLogger(__name__)


class SanicWServer(WServer):
    def __init__(self, app: Sanic, load_module='service', base_url='/', description="", version='', title="",
                 teamOfService="", install_apps=None, ) -> None:
        self.base_url = base_url
        self.description = description
        self.version = version
        self.title = title
        self.teamOfService = teamOfService
        self.app = app
        # install_apps = settings.INSTALLED_APPS
        mods = ["%s.%s" % (install_app, load_module) for install_app in install_apps]

        super().__init__(mods, True)

    def get_swagger(self, request, *args, **kwargs):
        hostname = request.host
        swagger = self.get_swagger_doc(hostname, self.base_url, self.description, self.version, self.title,
                                       self.teamOfService)
        return json(swagger)

    def get_route_info(self):
        urls = []
        for service in SERVICE.values():
            urls.extend(service.gen_route(base_url=self.base_url))
        if config.get("DEBUG"):
            urls.append(('swagger.json', self.get_swagger))
        return urls, ("/doc", self._default_static_doc)

    def init_route(self):
        restful_method = [u.upper() for u in RESTFUL_METHOD]
        route_info = self.get_route_info()
        for url, handle in route_info[0]:
            self.app.add_route(handler=handle, uri=url, methods=restful_method)
        self.app.static(route_info[1][0], route_info[1][1])
